// 用ts封装request请求

import axios from 'axios'

import type {
  AxiosInstance,
  AxiosRequestConfig,
  InternalAxiosRequestConfig,
  AxiosResponse
} from 'axios'

import { ElMessage } from 'element-plus'
import router from '../router'

import { useLoginStore } from '@/stores/login'

// 基本配置
const configs: AxiosRequestConfig = {
  baseURL: 'http://127.0.0.1:8888/api/private/v1/',
  timeout: 3000
}

class Http {
  axiosInstance: AxiosInstance
  constructor(configs: AxiosRequestConfig) {
    this.axiosInstance = axios.create(configs)
    this.interceptors()
  }

  private interceptors() {
    // 请求拦截
    this.axiosInstance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        const token = useLoginStore().token

        if (token) config.headers.Authorization = token //所有请求都要有token值(登录除外)
        return config
      },
      (err) => err
    )

    // 响应拦截
    this.axiosInstance.interceptors.response.use(
      (config: AxiosResponse) => {
        // 做一个错误捕捉 ==> 后端请求错误
        const status = config.data.meta.status

        if (/^2/.test(String(status))) return config

        interface IResponseObject {
          400: string
          401: string
          403: string
          404: string
          422: string
          500: string
        }
        const responseObject: IResponseObject = {
          400: '请求的地址不存在或者包含不支持的参数',
          401: '未授权',
          403: '禁止访问',
          404: '请求资源未存在',
          422: '创建时发生错误',
          500: '服务器错误'
        }

        const msg: string = responseObject[status as keyof IResponseObject]

        if (status == 401) router.push('/LoginVue')

        msg && ElMessage.warning(msg)

        return config
      },
      (err) => {
        // 网路处理
        const { message } = err

        if (message == 'Network Error') return ElMessage.error('网络错误,请检查后重试')
        if (message.includes('timeout')) return ElMessage.error('网络超时,请请重新发起请求')
        return err
      }
    )
  }
}

export default new Http(configs)
